<template>
  <div class="screening-container">
    <!-- 上传文件卡片 -->
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <span>上传文件</span>
          <el-button type="primary" size="small" @click="downloadTemplate">下载模板</el-button>
        </div>
      </template>
      
      <!-- 文件选择区域 -->
      <el-upload
        ref="uploadRef"
        class="upload-area"
        drag
        :auto-upload="false"
        :multiple="true"
        :limit="999999"
        :on-exceed="handleExceed"
        :before-upload="beforeUpload"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :file-list="selectedFiles"
      >
        <div class="upload-content">
          <el-icon class="upload-icon"><Upload /></el-icon>
          <p>点击或将文件拖拽到此处选择</p>
          <p>支持格式：Excel (xls, xlsx)</p>
          <p>无文件大小和数量限制</p>
          <p>免费使用，无需充值</p>
        </div>
      </el-upload>
      
      <!-- 文件列表和提交按钮 -->
      <div class="file-list-container" v-if="selectedFiles.length > 0">
        <div class="file-list-header">
          <span>待提交文件列表（{{ selectedFiles.length }}）</span>
          <div class="action-buttons">
            <el-button size="small" @click="clearFiles">清空</el-button>
            <el-button type="primary" size="small" :loading="uploading" @click="submitFiles">
              {{ uploading ? '正在提交...' : '提交筛查' }}
            </el-button>
          </div>
        </div>
      </div>
      
      <div class="upload-tip" v-if="selectedFiles.length === 0">
        <p>请选择要筛查的文件，系统将按照上传顺序依次处理文件，上传过程中请勿关闭页面</p>
        <p class="template-warning"><el-icon><Warning /></el-icon> 上传表格时，需严格按照模板，根据模板表头的文字修改</p>
      </div>
    </el-card>

    <!-- VIP广告弹窗 - 完全重新设计，移除所有可能导致竖排文字的元素 -->
    <div v-if="showAdPopup && currentAd" class="vip-dialog" :class="{ 'minimized': isMinimized }">
      <!-- 最小化状态 -->
      <div v-if="isMinimized" class="mini-view">
        <div class="mini-content">
          <span class="mini-title">限时特惠</span>
          <div class="mini-price">¥{{ currentPackage.price }}</div>
        </div>
        <el-button class="mini-btn" @click="showDetails">
          详情
        </el-button>
      </div>
      
      <!-- 完整状态 -->
      <div v-else class="full-view">
        <!-- 主标题栏 -->
        <div class="dialog-header">
          <!-- 顶部横幅 - 仅在新用户专享时显示 -->
          <div v-if="isNewUserPromo" class="new-user-banner">
            <el-icon><Present /></el-icon>
            <span>新用户专享 · 首充立减50元!</span>
          </div>
          
          <div class="header-main">
            <div class="title-area">
              <h2>{{ currentAd.scrollingInfo }}</h2>
              <p>{{ currentAd.description }}</p>
            </div>
            
            <div class="header-actions">
              <el-dropdown trigger="click" @command="handleAdSelect" class="ad-dropdown">
                <div class="custom-dropdown-btn">
                  <span>{{ currentAd?.scrollingInfo || '限时特惠' }}</span>
                  <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item 
                  v-for="ad in ads"
                  :key="ad.id"
                      :command="ad.id"
                      :class="{ 'is-active': selectedAdId === ad.id }"
                    >
                      {{ ad.scrollingInfo }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              
              <el-button class="close-btn" @click="minimizePopup">
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
          </div>
        </div>

        <!-- 会员选项 -->
        <div class="dialog-body">
          <div class="promo-header">
            <span>立即充值，享受VIP特权！</span>
          </div>
          
          <!-- 切换标签 -->
          <div class="tab-bar">
            <div 
              v-for="tab in ['svip', 'vip']"
              :key="tab"
              :class="['tab-item', { active: selectedTab === tab }]"
              @click="handleTabClick(tab)"
            >
              {{ tab.toUpperCase() }}会员
            </div>
          </div>

          <!-- 套餐选择 -->
          <div class="packages-grid">
            <div
              v-for="(pkg, index) in currentTabPackages"
              :key="index"
              :class="['package-item', { 
                recommended: index === 0,
                selected: selectedPackageIndex === index 
              }]"
              @click="selectedPackageIndex = index"
            >
              <div v-if="index === 0" class="recommend-badge">推荐</div>
              <div class="package-info">
                <h3>{{ pkg.duration }}会员</h3>
                <div class="price">¥{{ pkg.price }}</div>
                <div class="points">
                  <span>由</span>
                  <span class="gift-text">赠送{{ pkg.points }}点数</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 支付区域 -->
          <div class="payment-area">
            <div class="qr-section">
              <img :src="qrCodeImageUrl" alt="支付二维码" class="qr-code" />
              <p class="qr-hint">
                支付请添加客服联系方式
              </p>
            </div>
            
            <div class="order-details">
              <div class="detail-item">
                <span>活动截止</span>
                <span>{{ currentAd.formattedExpirationDate }}</span>
              </div>
              <div class="detail-item">
                <span>实付金额</span>
                <span class="price-text">¥{{ currentPackage.price }}</span>
              </div>
              <div class="detail-item">
                <span>赠送点数</span>
                <span class="points-text">{{ currentPackage.points }}点数</span>
              </div>
              <div class="contact-info">
                <span>联系电话：{{ currentAd.contactInfo || '400-123-4567' }}</span>
              </div>
              <el-button 
                type="primary" 
                class="pay-btn" 
                @click="goToRecharge"
              >
                立即充值
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.screening-container {
  padding: 20px;
  position: relative;
}

.upload-card {
  width: 600px;
  margin: 0 auto;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-area {
  text-align: center;
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  padding: 20px 0;
  background: #fbfdff;
  cursor: pointer;
}

.upload-content {
  color: #606266;
}

.upload-icon {
  font-size: 40px;
  color: #409eff;
  margin-bottom: 20px;
}

.upload-content p {
  margin: 5px 0;
  font-size: 14px;
}

.upload-tip {
  margin-top: 15px;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  text-align: center;
  
  .template-warning {
    margin-top: 8px;
    color: #E6A23C;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 500;
    
    .el-icon {
      margin-right: 5px;
      font-size: 16px;
    }
  }
}

// 文件列表容器
.file-list-container {
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.file-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  
  span {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
  }
  
  .action-buttons {
    display: flex;
    gap: 10px;
  }
}

/* 全新设计的VIP广告弹窗 */
.vip-dialog {
  position: fixed;
  z-index: 2000;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  
  /* 完整状态 */
  &:not(.minimized) {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 650px;
    max-height: 85vh;
    display: flex;
    flex-direction: column;
    background: #fff;
  }
  
  /* 最小化状态 */
  &.minimized {
    right: 20px;
    bottom: 20px;
    width: 180px;
    height: 70px;
    border-radius: 6px;
  }
}

/* 最小化视图样式 */
.mini-view {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(135deg, #ff6b6b, #ffa26b);
  color: white;
  height: 100%;
  padding: 0 12px;
  
  .mini-content {
    display: flex;
    flex-direction: column;
  }
  
  .mini-title {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 4px;
  }
  
  .mini-price {
    font-size: 18px;
    font-weight: 600;
  }
  
  .mini-btn {
    background: rgba(255, 255, 255, 0.2);
    border: none;
    color: white;
    font-size: 12px;
    padding: 4px 10px;
    border-radius: 4px;
    
    &:hover {
      background: rgba(255, 255, 255, 0.3);
    }
  }
}

/* 完整视图样式 */
.full-view {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

/* 对话框头部 */
.dialog-header {
  background: linear-gradient(135deg, #ff6b6b, #ffa26b);
  color: white;
}

/* 新用户横幅 */
.new-user-banner {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 8px;
  background: rgba(255, 255, 255, 0.15);
  font-weight: bold;
  
  .el-icon {
    animation: pulse 1.5s infinite;
  }
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

/* 主标题区域 */
.header-main {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  position: relative;
}

.title-area {
  flex: 1;
  padding-right: 20px;
  
  h2 {
    margin: 0 0 8px 0;
    font-size: 22px;
    font-weight: 600;
  }
  
  p {
    margin: 0;
    font-size: 14px;
    opacity: 0.9;
    line-height: 1.5;
  }
}

.header-actions {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.ad-dropdown {
  margin-right: 5px;
  
  .custom-dropdown-btn {
    background-color: #FF5F5F;
    color: white;
    border: none;
    padding: 6px 12px;
    font-size: 14px;
    font-weight: 600;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    text-shadow: 0 1px 2px rgba(0,0,0,0.2);
    
    &:hover {
      background-color: #FF7070;
    }
    
    .el-icon {
      margin-left: 4px;
      font-size: 12px;
    }
  }
  }
  
:deep(.el-dropdown-menu) {
  padding: 5px 0;
  min-width: 120px;
  border-radius: 8px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.15);
  border: none;
  
  .el-dropdown-item {
    padding: 10px 15px;
    font-size: 14px;
    line-height: 1.4;
    
    &:hover {
      background-color: #fff0f0;
      color: #ff6b6b;
    }
    
    &.is-active {
      color: #ff6b6b;
      font-weight: bold;
      background-color: #fff8f8;
    }
  }
}

.close-btn {
  background: transparent;
  border: none;
  color: white;
  padding: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  
  &:hover {
    background: rgba(255, 255, 255, 0.2);
  }
}

/* 对话框主体 */
.dialog-body {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: auto;
  background-color: #fff;
}

/* 促销提示 */
.promo-header {
  background-color: #f0f9ff;
  color: #409EFF;
  padding: 10px 16px;
  font-weight: 500;
  text-align: center;
  font-size: 15px;
  border-bottom: 1px solid #e0f2fe;
}

/* 选项卡 */
.tab-bar {
  display: flex;
  background: #fff;
  border-bottom: 1px solid #ebeef5;
}

.tab-item {
  flex: 1;
  padding: 14px 0;
  text-align: center;
  cursor: pointer;
  font-weight: 500;
  color: #606266;
  transition: all 0.3s;
  position: relative;
  
  &:hover {
    color: #ff6b6b;
  }
  
  &.active {
    color: #ff6b6b;
    font-weight: bold;
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 40%;
      height: 2px;
      background-color: #ff6b6b;
    }
  }
}

/* 套餐网格 */
.packages-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  padding: 16px;
}

.package-item {
  position: relative;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fff;
  
  &:hover {
    border-color: #ff6b6b;
  }
  
  &.recommended {
    border-color: #ff6b6b;
  }
  
  &.selected {
    border-color: #ff6b6b;
    background: #fff8f8;
}

.recommend-badge {
  position: absolute;
    top: -1px;
    right: -1px;
  background: #ff6b6b;
  color: white;
  font-size: 12px;
    padding: 3px 8px;
    border-top-right-radius: 8px;
    border-bottom-left-radius: 8px;
  font-weight: bold;
}

.package-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    
  h3 {
      margin: 0;
      font-weight: 600;
      font-size: 18px;
    color: #303133;
  }
  
  .price {
      font-size: 28px;
      font-weight: 700;
    color: #ff6b6b;
  }
  
  .points {
    display: flex;
    align-items: center;
      gap: 4px;
      color: #606266;
      font-size: 14px;
      
      .gift-text {
        color: #67c23a;
      }
    }
  }
}

/* 支付区域 */
.payment-area {
  display: grid;
  grid-template-columns: auto 1fr;
  gap: 20px;
  padding: 20px;
  background: #f9f9f9;
  border-top: 1px solid #ebeef5;

.qr-section {
  display: flex;
  flex-direction: column;
  align-items: center;
    padding: 16px;
    background: #fff;
    border-radius: 8px;
    border: 1px solid #ebeef5;

.qr-code {
  width: 150px;
  height: 150px;
      margin-bottom: 12px;
}

.qr-hint {
  font-size: 12px;
  color: #606266;
      margin: 0;
  }
}

.order-details {
    display: flex;
    flex-direction: column;
    gap: 16px;

.detail-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
      
      .price-text {
      color: #ff6b6b;
        font-weight: 600;
    }
      
      .points-text {
        color: #67c23a;
  }
}

    .contact-info {
      text-align: center;
      font-size: 13px;
  color: #909399;
      margin-top: 8px;
  }
  
    .pay-btn {
      margin-top: 16px;
      background: #ff6b6b;
      border-color: #ff6b6b;
      padding: 12px 0;
      font-size: 16px;
      
      &:hover {
        background: #ff5252;
        border-color: #ff5252;
      }
    }
  }
}
</style>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';
import { Upload, CaretBottom, Wallet, Close, Present, ArrowDown, Warning } from '@element-plus/icons-vue';
import { uploadFile, getPopupDetailsApi } from '@/api/main';
import axios from 'axios';

const router = useRouter();
const userStore = useUserStore();

// 文件上传相关
const uploadRef = ref(null);
const selectedFiles = ref([]);
const uploading = ref(false);

// 文件选择处理
const handleFileChange = (file, fileList) => {
  selectedFiles.value = fileList;
};

const handleFileRemove = (file, fileList) => {
  selectedFiles.value = fileList;
};

const clearFiles = () => {
  selectedFiles.value = [];
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
};

const handleExceed = (files) => {
  ElMessage.warning(`文件数量过多，建议分批上传`);
};

// 提交前文件检查
const beforeUpload = (file) => {
  const isExcel =
    file.type === 'application/vnd.ms-excel' ||
    file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  if (!isExcel) {
    ElMessage.error('上传文件必须是 Excel 格式!');
    return false;
  }
  return true;
};

// 批量提交文件
const submitFiles = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning('请先选择需要筛查的文件');
    return;
  }
  
  uploading.value = true;
  let successCount = 0;
  let failCount = 0;
  
  try {
    // 按顺序上传文件
    for (const file of selectedFiles.value) {
      try {
        const formData = new FormData();
        formData.append('file', file.raw);
        
        const response = await uploadFile(formData);
        if (response.data.code === 201) {
          ElMessage.error(`文件 ${file.name} 上传失败: ${response.data.data}`);
          failCount++;
        } else {
          successCount++;
        }
      } catch (err) {
        console.error(`文件 ${file.name} 上传出错:`, err);
        failCount++;
        // 优先显示data字段中的错误信息（后端验证错误通常在这里）
        if (err.response?.data?.code === 201) {
          const errorMsg = err.response.data.data || err.response.data.message || '上传失败';
          ElMessage.error(`文件 ${file.name} 上传失败: ${errorMsg}`);
        } else if (err.response?.data?.data) {
          // 处理其他错误码但data字段有内容的情况
          ElMessage.error(`文件 ${file.name} 上传失败: ${err.response.data.data}`);
        } else if (err.response?.data?.message) {
          ElMessage.error(`文件 ${file.name} 上传失败: ${err.response.data.message}`);
        } else if (err.message) {
          ElMessage.error(`文件 ${file.name} 上传失败: ${err.message}`);
        } else {
          ElMessage.error(`文件 ${file.name} 上传失败，请稍后再试`);
        }
      }
    }
    
    if (successCount > 0) {
      ElMessage.success(`成功提交 ${successCount} 个文件，系统将按照提交顺序依次处理`);
      ElMessage.info('请在"导出结果"中查看处理进度');
      clearFiles(); // 清空已提交的文件
    }
    
    if (failCount > 0) {
      ElMessage.warning(`${failCount} 个文件提交失败，请检查后重试`);
    }
  } finally {
    uploading.value = false;
  }
};

// 广告弹窗状态
const showAdPopup = ref(false);
const isMinimized = ref(false);
const ads = ref([]); // 所有广告数据
const selectedAdId = ref(null); // 当前选中的广告ID

// 当前广告数据
const currentAd = computed(() => {
  const selected = ads.value.find(ad => ad.id === selectedAdId.value);
  return selected || (ads.value.length > 0 ? ads.value[0] : null);
});

// 处理二维码图片URL
const qrCodeImageUrl = computed(() => {
  if (!currentAd.value || !currentAd.value.qrCodeUrl) return '';
  
  // 如果已经是完整的URL（以http开头），则直接返回
  if (currentAd.value.qrCodeUrl.startsWith('http')) {
    return currentAd.value.qrCodeUrl;
  }
  
  // 如果是相对路径，确保路径正确
  return currentAd.value.qrCodeUrl;
});

// 是否为新用户专享
const isNewUserPromo = computed(() => {
  return currentAd.value && currentAd.value.scrollingInfo 
    && currentAd.value.scrollingInfo.includes('新用户专享');
});

// 当前广告的套餐数据
const parsedVipPackages = computed(() => {
  return currentAd.value && currentAd.value.vipPackages 
    ? JSON.parse(currentAd.value.vipPackages) 
    : [];
});

// 将套餐数据分为 VIP 和 SVIP 两组
const vipPackages = computed(() => {
  const packages = parsedVipPackages.value;
  return packages.slice(Math.ceil(packages.length / 2));
});

const svipPackages = computed(() => {
  const packages = parsedVipPackages.value;
  return packages.slice(0, Math.ceil(packages.length / 2));
});

// 根据当前选中的选项卡获取对应的套餐列表
const currentTabPackages = computed(() => {
  return selectedTab.value === 'vip' ? vipPackages.value : svipPackages.value;
});

// 当前选中套餐
const currentPackage = computed(() => {
  return currentTabPackages.value[selectedPackageIndex.value] || {};
});

// 获取广告数据并预处理日期
const fetchAdData = async () => {
  try {
    const response = await getPopupDetailsApi();
    console.log('API Response:', response);
    if (response.data.code === 200) {
      // 预处理数据，格式化日期
      ads.value = response.data.data.map(ad => ({
        ...ad,
        formattedExpirationDate: ad.expirationDate 
          ? ad.expirationDate.split('T')[0] 
          : '暂无日期'
      }));
      console.log('Processed ads:', ads.value);
      if (ads.value.length > 0) {
        selectedAdId.value = ads.value[0].id; // 默认选中第一个广告
      }
    } else {
      console.error('API返回非成功状态:', response.data);
    }
  } catch (error) {
    console.error('获取广告数据失败:', error);
    ads.value = []; // 失败时清空数据
  }
};

// 切换广告
const changeAd = (adId) => {
  selectedAdId.value = adId;
  selectedPackageIndex.value = 0; // 重置套餐选择
};

// 下拉菜单的处理函数
const handleAdSelect = (adId) => {
  changeAd(adId);
};

// 从 localStorage 获取最小化状态
const getStoredMinimizeState = () => {
  const stored = localStorage.getItem('adPopupMinimized');
  return stored === 'true'; // 确保返回布尔值
};

// 保存最小化状态到 localStorage
const saveMinimizeState = (state) => {
  localStorage.setItem('adPopupMinimized', state);
};

// 最小化/展开控制
const minimizePopup = () => {
  isMinimized.value = true;
  saveMinimizeState(true);
};

const showDetails = () => {
  isMinimized.value = false;
  saveMinimizeState(false);
};

// 初始化弹窗状态
const initializePopupState = () => {
  const storedState = getStoredMinimizeState();
  showAdPopup.value = ads.value.length > 0; // 只有当有广告数据时才显示
  isMinimized.value = storedState;
};

// 监听路由变化
watch(
  () => router.currentRoute.value.path,
  async (newPath, oldPath) => {
    if (newPath === oldPath) return; // 避免相同路由重复触发

    if (ads.value.length === 0) {
      // 如果还没有广告数据，获取数据
      await fetchAdData();
    }
    
    // 恢复存储的状态
    initializePopupState();
  },
  { immediate: true }
);

// 监听用户登录状态变化
watch(
  () => userStore.userInfo,
  (newUserInfo, oldUserInfo) => {
    if (!newUserInfo && oldUserInfo) { // 用户退出登录
      localStorage.removeItem('adPopupMinimized'); // 清空最小化状态
      isMinimized.value = false; // 恢复最大化
      showAdPopup.value = ads.value.length > 0;
    }
  }
);

// 组件挂载时初始化
onMounted(async () => {
  await fetchAdData();
  initializePopupState();
});

const selectedTab = ref('svip'); // 默认选中VIP会员
const selectedPackageIndex = ref(0); // 默认选中第一个套餐

// 处理选项卡点击
const handleTabClick = (tab) => {
  if (tab === selectedTab.value) return;
  selectedTab.value = tab;
  selectedPackageIndex.value = 0;
};

// 添加前往充值页面的方法
const goToRecharge = () => {
  // 获取当前选中的广告标题（作为套餐类型）
  const packageType = currentAd.value ? currentAd.value.scrollingInfo : '';
  
  // 获取当前选中套餐的信息
  const packageInfo = {
    packageType: packageType, // 套餐类型（弹窗标题）
    price: currentPackage.value.price, // 价格
    duration: currentPackage.value.duration, // 时长
    points: currentPackage.value.points // 点数
  };
  
  // 跳转到充值页面并传递参数
  router.push({
    path: '/main/recharge',
    query: packageInfo
  });
  
  // 最小化广告弹窗
  minimizePopup();
};

// 下载模板函数
const downloadTemplate = async () => {
  try {
    ElMessage.success('模板下载中...');
    console.log('开始下载模板文件');
    
    // 获取API基础URL
    // 优先使用环境变量，如果未定义则构建基于当前域名的绝对路径
    let baseUrl = '';
    if (import.meta.env.VITE_APP_BASE_API) {
      // 如果是相对路径如 /api，转换为绝对路径
      if (import.meta.env.VITE_APP_BASE_API.startsWith('/')) {
        baseUrl = `${window.location.origin}${import.meta.env.VITE_APP_BASE_API}`;
      } else {
        baseUrl = import.meta.env.VITE_APP_BASE_API;
      }
    } else {
      // 默认使用当前域名
      baseUrl = `${window.location.origin}/api`;
    }
    
    // 确保路径不重复
    const apiPath = '/admin/system/sysDoc/download-template';
    const url = baseUrl.endsWith('/') ? baseUrl + apiPath.substring(1) : baseUrl + apiPath;
    
    console.log('下载模板请求URL:', url);
    
    try {
      await downloadWithUrl(url);
    } catch (error) {
      console.error('使用第一个URL下载失败，尝试备用路径:', error);
      
      // 尝试备用路径 - 相对路径
      const fallbackUrl = `/admin/system/sysDoc/download-template`;
      console.log('尝试备用URL:', fallbackUrl);
      
      await downloadWithUrl(fallbackUrl);
    }
  } catch (error) {
    console.error('所有下载尝试均失败:', error);
    ElMessage.error('下载模板失败，请稍后再试或联系管理员');
    
    // 显示更详细的错误信息，帮助用户排查问题
    setTimeout(() => {
      ElMessage.info('如果问题持续，请尝试刷新页面或联系技术支持');
    }, 2000);
  }
};

// 封装下载逻辑为独立函数
const downloadWithUrl = async (url) => {
  // 准备请求头
  const headers = {
    'Cache-Control': 'no-cache'
  };
  
  // 使用axios发送请求，保留cookie以便自动处理身份验证
  const response = await axios({
    url,
    method: 'GET',
    responseType: 'blob',
    timeout: 30000,
    headers,
    withCredentials: true
  });
  
  // 检查响应有效性
  if (!response.data || response.data.size === 0) {
    throw new Error('下载的文件为空');
  }
  
  console.log('下载成功，响应状态:', response.status);
  console.log('响应类型:', response.headers['content-type']);
  
  // 创建blob链接并触发下载
  const contentType = response.headers['content-type'];
  
  // 检查是否为错误响应（有时API会返回JSON错误信息而不是文件）
  if (contentType && contentType.includes('application/json')) {
    // 可能是返回的错误信息，尝试解析
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = function() {
        try {
          const jsonResponse = JSON.parse(reader.result);
          console.error('服务器返回错误JSON:', jsonResponse);
          reject(new Error(jsonResponse.msg || '下载失败，服务器返回错误'));
        } catch (e) {
          console.error('解析JSON失败:', e);
          reject(new Error('下载失败，无法解析服务器响应'));
        }
      };
      reader.readAsText(response.data);
    });
  }
  
  const blob = new Blob([response.data], { 
    type: contentType || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
  });
  
  const blobUrl = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = blobUrl;
  
  // 获取文件名，默认为"筛查模板.xlsx"
  const disposition = response.headers['content-disposition'];
  let filename = '筛查模板.xlsx';
  if (disposition && disposition.indexOf('attachment') !== -1) {
    const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
    const matches = filenameRegex.exec(disposition);
    if (matches != null && matches[1]) {
      filename = matches[1].replace(/['"]/g, '');
    }
  }
  
  link.setAttribute('download', decodeURIComponent(filename));
  document.body.appendChild(link);
  link.click();
  window.URL.revokeObjectURL(blobUrl);
  document.body.removeChild(link);
  ElMessage.success('模板下载成功');
};
</script>